﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SuperKit {
    public class FastPackUpdate : CommandExecutor {

        private List<FileInfo> Files { get; set; }
        private string Prefix { get; set; }

        public FastPackUpdate(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
            Prefix = arg.GetParameter("-prefix");
        }

        public override void Execute() {
            Thread t = new Thread(OnProcess);
            t.Start();
        }

        private void OnProcess() {
            if (Directory.Exists(FilePath)) {
                Files = Kit.GetAllFiles(null, new DirectoryInfo(FilePath), Kit.PAK_EXTS);
                foreach (var i in Files) {
                    Update(i.FullName);
                }
            } else if (File.Exists(FilePath)) {
                FileInfo fileInfo = new(FilePath);
                string unpack_path = Path.Combine(fileInfo.DirectoryName, Path.GetFileNameWithoutExtension(fileInfo.Name));
                Update(FilePath);
            }

            End();
        }

        private void Update(string filename) {
            Flush("Update Database: {0}, Prefix:{1}", filename, Prefix);

            string script_args = $"-update \"{filename}\" -p {Prefix}";
            Flush("{0} {1}", FastPackExe.FAST_PACK_PY, script_args);
            FastPackExe.RunPythonScript(FastPackExe.FAST_PACK_PY, script_args);
        }
    }
}
